import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { UsersService } from '../users/users.service';
import { LoginDto } from './dto/login.dto';
import { JwtResponseDto } from './dto/jwt-response.dto';

// 管理员注册校验码（生产环境应该放在环境变量中）
const ADMIN_REGISTRATION_CODE = 'FACTORY_ADMIN_2025';

@Injectable()
export class AuthService {
  constructor(
    private usersService: UsersService,
    private jwtService: JwtService,
  ) {}

  async validateUser(loginDto: LoginDto): Promise<any> {
    const user = await this.usersService.validateUser(
      loginDto.employeeId,
      loginDto.password,
    );
    return user;
  }

  async login(user: any): Promise<JwtResponseDto> {
    const payload = { 
      employeeId: user.employeeId, 
      sub: user.id,
      role: user.role 
    };
    
    const accessToken = this.jwtService.sign(payload);
    
    return new JwtResponseDto(accessToken, user);
  }

  async register(createUserDto: any): Promise<JwtResponseDto> {
    // 默认注册为普通用户
    const userDto = {
      ...createUserDto,
      role: 'user', // 强制设置为普通用户
    };

    const user = await this.usersService.create(userDto);
    return this.login(user);
  }

  async registerAdmin(createUserDto: any, adminCode: string): Promise<JwtResponseDto> {
    // 验证管理员注册码
    if (adminCode !== ADMIN_REGISTRATION_CODE) {
      throw new UnauthorizedException('管理员注册码错误');
    }

    // 注册管理员用户
    const userDto = {
      ...createUserDto,
      role: 'admin',
    };

    const user = await this.usersService.create(userDto);
    return this.login(user);
  }
}